import java.io.*;
import java.net.*;
import java.util.*;

public class GroupDispatcher{
	public int numberOfElevators; //Hardcoded number of elevators
	
	Vector<ElevatorWorker> freeElevators;
	Vector<ElevatorWorker> upElevators;
	Vector<ElevatorWorker> downElevators;
	public ServerSocket socket;
	
	public GroupDispatcher() throws IOException{
		numberOfElevators = 0;
		socket = new ServerSocket(1337);
		freeElevators = new Vector<ElevatorWorker>();
		downElevators = new Vector<ElevatorWorker>();
		upElevators = new Vector<ElevatorWorker>();
	}
	public void run(){
		
		GDElevatorInit ei = new GDElevatorInit(this);
		GDMessageHandler mh= new GDMessageHandler(this);
		GDStatusCheck sc = new GDStatusCheck(this);
		
		ei.start();
		mh.start();
		sc.start();
		
	
	}
	public static void main(String[] args) throws IOException{
		GroupDispatcher gd = new GroupDispatcher();
		gd.run();		
	}
	public ElevatorWorker determineElevator(int floor, char direction){
		ElevatorWorker ew = null;
		while(true){
			if(freeElevators.size() != 0){ //first case: a free elevator is available.
				ew = freeElevators.remove(0);
				if(direction == 'D'){
					downElevators.add(ew);
				}
				if(direction == 'U'){
					upElevators.add(ew);
				}
				return ew;
				
			}else{ //second case: an elevator in same direction is available and is on right path
				if(direction == 'D'){
					for(int i = 0; i < downElevators.size(); i++){
						if(downElevators.get(i).getFloor() > floor){
							ew = downElevators.get(i);
							return ew;
						}
					}				
				}
				if(direction == 'U'){
					for(int i = 0; i < upElevators.size(); i++){
						if(upElevators.get(i).getFloor() < floor){
							ew = upElevators.get(i);
							return ew;
						}
					}
				}
			}
			//third case: first elevator with path list <= 2
			if(direction == 'D'){
				for(int i = 0; i < downElevators.size(); i++){
					if(downElevators.get(i).floorList.length <= 3){
						ew = downElevators.get(i);
						return ew;
					}
				}
			}else if(direction == 'U'){
				for(int i = 0; i < upElevators.size(); i++){
					if(upElevators.get(i).floorList.length <= 3){
						ew = upElevators.get(i);
						return ew;
					}
				}
			}
		
			//fourth case: pick random elevator
			if(downElevators.size() != 0){
				ew = downElevators.remove(0);
				return ew;
			}
			if(upElevators.size() != 0){
				ew = upElevators.remove(0);	
				return ew;
			}
		
		}
	}
}

